using System;
using System.IO;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace Function.HotUpdate
{
    // 升级大版本的时候，尝试清理之前的缓存，避免新老数据不兼容导致的bug
    public static class CacheEraser
    {
        const string _key = "__CacheEraser_InstalledVersion";

        // 安装版本号，非remote版本号，形如1.2.3
        public static void TryErase(string binVersion)
        {
            UnityEngine.Debug.Log($"[CacheEraser] TryErase {binVersion}");
            var oldVersion = PlayerPrefs.GetString(_key, "");
            var needClear = false;
            if (string.IsNullOrEmpty(oldVersion))
            {
                needClear = true;
            }
            else
            {
                Version oldInfo = new Version(oldVersion);
                Version newInfo = new Version(binVersion);

                // 只要appVersion不一致，就清理缓存    
                if (oldInfo.Major != newInfo.Major
                    || oldInfo.Minor != newInfo.Minor
                    || oldInfo.Build != newInfo.Build)
                {
                    needClear = true;
                }
            }

            if (needClear)
            {
                UnityEngine.Debug.Log($"[CacheEraser] clear cache for new version {binVersion}");
                ClearCache();
                PlayerPrefs.SetString(_key, binVersion);
            }
        }

        private static string GetAddressablesCachePath()
        {
            // 这是Addressables默认使用的缓存路径，根据你的配置可能需要调整
            string cachePath = Path.Combine(Application.persistentDataPath, "com.unity.addressables");
            return cachePath;
        }

        private static void ClearCache()
        {
            try
            {
                // 例如，删除指定目录下的缓存文件
                string cachePath = Application.persistentDataPath + "/Cache";
                if (Directory.Exists(cachePath))
                {
                    UnityEngine.Debug.Log($"[CacheEraser] clear cache {cachePath}");
                    Directory.Delete(cachePath, true);
                }

                string addressablesCachePath = GetAddressablesCachePath();
                if (Directory.Exists(addressablesCachePath))
                {
                    UnityEngine.Debug.Log($"[CacheEraser] clear cache {addressablesCachePath}");
                    Directory.Delete(addressablesCachePath, true);
                }

                Addressables.ClearResourceLocators();


                // // 清理 PlayerPrefs -- 谨慎，一般不需要
                // PlayerPrefs.DeleteAll();   
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogError($"[CacheEraser] clear cache failed {e}");
            }
        }
    }
}